<template>
<div>
 <!-- 面包屑 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>权限列表</el-breadcrumb-item>
  </el-breadcrumb>
   <!-- 卡片视图 -->
  <el-card class="box-card" style="width:100%">
      <!-- 警告区域 -->
    <el-alert
    title="添加商品"
    type="info"
    center
    show-icon
    :closable="false">
    </el-alert>
  <!-- 步骤条 -->
  <el-steps :active="activeTabs-0" align-center finish-status="success">
    <el-step title="基本信息"></el-step>
    <el-step title="商品参数"></el-step>
    <el-step title="商品属性"></el-step>
    <el-step title="商品图片"></el-step>
    <el-step title="商品内容"></el-step>
    <el-step title="完成"></el-step>
  </el-steps>
  <!-- Tab切换 -->
   <el-form label-position="top" ref="addGoodsForm" :model="addGoodsForm" :rules="addGoodsRules" label-width="80px">
     <!-- 基本信息 -->
     <el-tabs v-model="activeTabs" @tab-click="tabsClick" :before-leave="beforeLeave" tab-position="left">
       <el-tab-pane label="基本信息" name="0">
          <el-form-item prop="goods_name" label="商品名称">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item prop="goods_price" label="商品价格">
            <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item prop="goods_weight" label="商品重量">
            <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item prop="goods_number" label="商品数量">
            <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <!-- 级联选择器，options可选项的数据 -->
           <el-cascader
             v-model="addGoodsForm.goods_cat"
             :options="cates"
             :props= props>
             </el-cascader>
          </el-form-item>
          <!-- 商品分类 -->
       </el-tab-pane>

       <!-- 商品参数 -->
       <el-tab-pane label="商品参数" name="1">
          <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
            <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(checkboxItem, index) in item.attr_vals" :key="index"
                :label="checkboxItem"></el-checkbox>
              </el-checkbox-group>
          </el-form-item>
       </el-tab-pane>

       <!-- 商品属性 -->
       <el-tab-pane label="商品属性" name="2">
         <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
           <el-input v-model="item.attr_vals">{{item.attr_vals}}</el-input>
         </el-form-item>
       </el-tab-pane>

       <!-- action接口地址，axios对该组件不起作用，写完整的接口地址 -->
       <!-- 上传商品图片 -->
       <el-tab-pane label="商品图片" name="3">
         <el-upload
           class="upload-demo"
           action="https://www.liulongbin.top:8888/api/private/v1/upload"
           :on-preview="handlePreview"
           :on-remove="handleRemove"
           :on-success="uploadSuccess"
           :headers="uploadHeaders"
           list-type="picture">
           <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
       </el-tab-pane>

       <!-- 商品内容 -->
       <el-tab-pane label="商品内容" name="4">
           <quill-editor></quill-editor>
           <el-button @click="AddGoods" type="primary">添加内容</el-button>
       </el-tab-pane>
     </el-tabs>
    </el-form>
 </el-card>

 <!-- 预览图片 -->
 <el-dialog
   title="图片预览"
   :visible.sync="previewDialogVisible"
   width="50%">
   <img style="width: 100%;" :src="imgUrl" />
   <span slot="footer" class="dialog-footer">
     <el-button @click="previewDialogVisible = false">取 消</el-button>
     <el-button type="primary" @click="previewDialogVisible = false">确 定</el-button>
   </span>
</el-dialog>
</div>
</template>

<script>
import { cloneDeep } from 'loadsh'
export default {
  data () {
    return {
      activeTabs: '0',
      // 表格数据
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        goods_cat: [2273, 2274, 2275], // 级联选择器的双向数据绑定,要和form表单一起提交
        pics: []
      },
      // 校验规则
      addGoodsRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }]
      },
      props: {
        expandTrigger: 'hover',
        label: 'cat_name', // 要显示哪个数据
        value: 'cat_id' // 要把哪个数据保存下来
      },
      cates: [],
      // 商品动态参数
      manyData: [],
      onlyData: [],
      // 上传图片请求头
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      imgUrl: '',
      previewDialogVisible: false
    }
  },

  created () {
    this.getGoodsCate()
  },

  // 三级分类Id值保存下来
  computed: {
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message('获取数据失败')
      this.cates = res.data
      // console.log(this.addGoodsForm.goods_cat)
    },
    // 离开某一项标签触发
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0') {
        if (this.addGoodsForm.goods_cat.length !== 3) {
          this.$message.error('请选择三级分类商品')
          return false
        }
      }
    },
    // 点击事件
    async tabsClick () {
      // 动态参数
      if (this.activeTabs === '1') {
        // console.log('点击了分类参数')
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('获取数据失败')
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
      // 静态属性
      } else if (this.activeTabs === '2') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取数据失败')
        // res.data.forEach(item => {
        //   item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        // })
        this.onlyData = res.data
        // console.log(this.onlyData)
      }
    },
    // 点击预览的回调
    handlePreview (file) {
      this.imgUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 点击移除图片的回调
    handleRemove (file) {
      const filePath = file.response.data.temp_path
      // 通过findidexx寻找到要删除这一项的索引
      const index = this.addGoodsForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      // 通过索引进行删除
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 上传成功的提示
    uploadSuccess (res) {
      // console.log(res)
      this.addGoodsForm.pics.push({
        pic: res.data.temp_path
      })
    },
    // 点击添加商品
    AddGoods () {
      this.$refs.addGoodsForm.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息')
        // this.addGoodsForm :控制页面的数据
        // addGoodsForm;交给后台的数据
        // 序列化深拷贝 JSON。parse(JSON.stringfy(this.addGoodsForm))
        const addGoodsForm = cloneDeep(this.addGoodsForm)
        addGoodsForm.goods_cat = addGoodsForm.goods_cat.join(',')
        // attrs：传递动态参数和静态属性
        // console.log(addGoodsForm, this.addGoodsForm)
        addGoodsForm.attrs = []
        // 整理attr数据
        this.manyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        // console.log(addGoodsForm)
        const { data: res } = await this.$axios.post('goods', addGoodsForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message(res.meta.msg)
        this.addGoodsForm = res.data
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-checkbox {
  margin-right: 0;
}
</style>
